package com.revenant.driver.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citylist.Toast.ToastUtils;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.revenant.driver.R;
import com.revenant.driver.adapter.Driver.ChePaiItemAdapter;
import com.revenant.driver.adapter.Driver.SearchEmptyAdapter;
import com.revenant.driver.adapter.SelectCarNumberNewBeanAdapter;
import com.revenant.driver.base.BaseActivity;
import com.revenant.driver.bean.Driver.ChePaiBean;
import com.revenant.driver.bean.Driver.LocationChePaiBean;
import com.revenant.driver.bean.PersonalCommentShowBean;
import com.revenant.driver.bean.SelectCarNewBean;
import com.revenant.driver.bean.ShipperBean.ShipperPublishedBean;
import com.revenant.driver.bean.selectcarnumber.StatusNormalBean;
import com.revenant.driver.bean.selectcarnumber.StatusNormalSecondBean;
import com.revenant.driver.bean.selectcarnumber.StatusTabbeddNormalBean;
import com.revenant.driver.bean.selectcarnumber.StatusTabbeddNormalSecondBean;
import com.revenant.driver.utils.GsonUtil;
import com.revenant.driver.utils.LocatinNoDataService;
import com.revenant.driver.utils.LocationService;
import com.revenant.driver.utils.SPUtils;
import com.revenant.driver.utils.Utils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.revenant.driver.utils.Constants.Comment_PerSonal_Show;
import static com.revenant.driver.utils.Constants.Driver_Add_CarNo;
import static com.revenant.driver.utils.Constants.Driver_CarNo_Search;
import static com.revenant.driver.utils.Constants.Driver_JustOrder_Order_Second_New;
import static com.revenant.driver.utils.Constants.Driver_JustOrder_Order_Second_New_0825;

public class DriverPublishEmptyActivity extends BaseActivity {
    CityPickerView mPickerstart = new CityPickerView();

    CityPickerView mPickerend = new CityPickerView();
    @BindView(R.id.load_text)
    TextView loadText;
    @BindView(R.id.load_detail_text)
    EditText loadDetailText;
    @BindView(R.id.unload_text)
    TextView unloadText;
    @BindView(R.id.unload_detail_text)
    EditText unloadDetailText;
    @BindView(R.id.car_num)
    TextView carNum;
    @BindView(R.id.car_type)
    TextView carType;
    @BindView(R.id.car_pho)
    EditText carPho;
    @BindView(R.id.car_name)
    TextView carName;
    @BindView(R.id.show_driver_info)
    LinearLayout showDriverInfo;
    @BindView(R.id.driver_info_click)
    TextView driverInfoClick;
    @BindView(R.id.show_text)
    LinearLayout showText;
    @BindView(R.id.publishbtn)
    Button publishbtn;
    @BindView(R.id.shippername)
    ImageView shippername;
    @BindView(R.id.commentscore)
    TextView commentscore;
    @BindView(R.id.shipperscore)
    TextView shipperscore;
    @BindView(R.id.jiaoyi)
    TextView jiaoyi;
    @BindView(R.id.pingjia)
    TextView pingjia;
    @BindView(R.id.show_new_old)
    RelativeLayout showNewOld;
    private Context context;
    private String startcode = "110101";
    private String endcode = "110100";

    private ChePaiItemAdapter mSearchEmptyAdapter;


    private String carno = "";
    AMapLocation location;
    private ArrayList<MultiItemEntity> list;
    private int selectone = -1;
    private SelectCarNumberNewBeanAdapter carnumberadapter;
    private AlertDialog alertDialog;

    @Override
    public int getContentViewResId() {
        return R.layout.activity_driver_publish_car;
    }

    @Override
    public void initView() {

        if (LocationService.getLastLocation() != null) {
            location = LocationService.getLastLocation();
        } else if (LocatinNoDataService.getLastLocation() != null) {
            location = LocatinNoDataService.getLastLocation();
        } else {
            Intent serviceIntend = new Intent(this, LocatinNoDataService.class);
            startService(serviceIntend);
        }


        context = this;
        mPickerstart.init(context);
        mPickerend.init(context);
        setcenterTitle("发布空车");

    }

    @Override
    public void initData() {
        getpseronal();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void leftbarclick() {
        super.leftbarclick();
        finish();
    }

    @OnClick({R.id.load_text, R.id.unload_text, R.id.car_num, R.id.publishbtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.load_text:
                alertareastrat();
                break;
            case R.id.unload_text:
                alertareaend();
                break;
            case R.id.car_num:
                selectcarnumber();
//                getDriverEmpty(SPUtils.getAccounId(context));
                break;
            case R.id.publishbtn:
                if (Utils.isFastClick()) {
                    showDig();
                    if (LocatinNoDataService.getLastLocation() != null) {
                        location = LocatinNoDataService.getLastLocation();
                    }

                    pushGoods(loadText.getText().toString(), unloadText.getText().toString(), startcode, endcode, loadDetailText.getText().toString(), unloadDetailText.getText().toString(), carno);
                }

                break;
        }
    }

    private void alertareastrat() {
        CityConfig cityConfig = new CityConfig.Builder()
                .confirTextColor("#1E90FF")
                .cancelTextColor("#1E90FF")
                .districtCyclic(false)
                .cityCyclic(false)
                .provinceCyclic(false)
                .build();
        mPickerstart.setConfig(cityConfig);

        mPickerstart.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                startcode = district.getId();
                loadText.setText(province.getName() + "-" + city.getName() + "-" + district.getName());
            }

            @Override
            public void onCancel() {
                ToastUtils.showLongToast(context, "已取消");
            }
        });

        mPickerstart.showCityPicker();
    }

    private void alertareaend() {
        CityConfig cityConfig = new CityConfig.Builder()
                .confirTextColor("#1E90FF")
                .cancelTextColor("#1E90FF")
                .districtCyclic(false)
                .cityCyclic(false)
                .provinceCyclic(false)
                .build();
        mPickerend.setConfig(cityConfig);

        mPickerend.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                endcode = district.getId();

                unloadText.setText(province.getName() + "-" + city.getName() + "-" + district.getName());
            }

            @Override
            public void onCancel() {
                ToastUtils.showLongToast(context, "已取消");
            }
        });

        mPickerend.showCityPicker();
    }

    private void getDriverEmpty(int id) {
        OkGo.<String>get(Driver_CarNo_Search)

                .params("id", id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        ChePaiBean g = GsonUtil.parseJsonWithGson(response.body(), ChePaiBean.class);
                        if (g.getCode().equals("0")) {

                            if (g.getData().getNumberList().size() > 0) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                View view = getLayoutInflater().inflate(R.layout.chepaiselect, null);
                                RecyclerView type = view.findViewById(R.id.recyclerview);
                                mSearchEmptyAdapter = new ChePaiItemAdapter();
                                mSearchEmptyAdapter.setNewData(g.getData().getNumberList());
                                type.setLayoutManager(new LinearLayoutManager(context));
                                type.setAdapter(mSearchEmptyAdapter);


                                builder.setView(view);
                                final AlertDialog alertDialog = builder.show();
                                mSearchEmptyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                        alertDialog.dismiss();
                                        String s = mSearchEmptyAdapter.getData().get(position);
                                        carno = s;
                                        carNum.setText(s);
                                    }
                                });
                            } else {
                                finish();
                                showToast("车辆目前为空,请添加车辆");
                                startActivity(DriverEmptyCarManageActivity.class);

                            }

                        } else {
                            showToast(g.getMsg());
                        }
                    }
                });

    }

    private void pushGoods(String loading, String unloading, String loadCode, String unloadCode, String loadCodeDetails, String unloadCodeDetails, String carNo) {


        OkGo.<String>post(Driver_Add_CarNo)

                .params("driverId", SPUtils.getAccounId(this))
                .params("loadCode", loadCode)
                .params("unloadCode", unloadCode)
                .params("loadCodeDetails", loadCodeDetails)
                .params("unloadCodeDetails", unloadCodeDetails)
                .params("carNo", carNo)
                .params("loading", loading)
                .params("unloading", unloading)
                .params("x", location.getLongitude())
                .params("y", location.getLatitude())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        ShipperPublishedBean shipperPublishedBean = GsonUtil.parseJsonWithGson(response.body(), ShipperPublishedBean.class);
                        if (shipperPublishedBean.getCode().equals("0")) {
                            showToast(shipperPublishedBean.getMsg());
                            finish();
                        } else {
                            showToast(shipperPublishedBean.getMsg());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();
                    }
                });
    }


    private void selectcarnumber() {
        OkGo.<String>get(Driver_JustOrder_Order_Second_New_0825)

                .params("id", SPUtils.getAccounId(this))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        SelectCarNewBean g = GsonUtil.parseJsonWithGson(response.body(), SelectCarNewBean.class);
                        if (g.getCode().equals("0")) {

                            if (g.getData().size() > 0) {
                                if (list != null) {
                                    list.clear();
                                } else {
                                    list = new ArrayList<>();
                                }
                                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                View view = getLayoutInflater().inflate(R.layout.chepaiselect, null);
                                RecyclerView type = view.findViewById(R.id.recyclerview);
                                TextView cancel = view.findViewById(R.id.cancel);
                                TextView ok = view.findViewById(R.id.confirm);
                                cancel.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        alertDialog.dismiss();
                                    }
                                });

                                ok.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        alertDialog.dismiss();

                                        if (list != null){
                                            if (selectone == -1) {
                                                showToast("请选择车辆");
                                            } else {
                                                StatusNormalSecondBean multiItemEntity = (StatusNormalSecondBean) carnumberadapter.getData().get(selectone);
                                                String s = multiItemEntity.cardNumber;
                                                carno = s;
                                                carNum.setText(s);
                                                if (multiItemEntity.isConsummate==0){
                                                    Bundle bundlecar = new Bundle();
                                                    bundlecar.putInt("cartype", 0);
                                                    bundlecar.putInt("cartbuqanId", multiItemEntity.carDriverId);
                                                    startActivity(BuQuanGuaCheActivity.class, bundlecar);
                                                    finish();
                                                }
                                            }
                                        }else {
                                            finish();
                                            showToast("车辆目前为空,请添加车辆");
                                            startActivity(DriverEmptyCarManageActivity.class);
                                        }



                                    }
                                });
                                if (g.getData() != null) {

                                    for (int i = 0; i < g.getData().size(); i++) {

                                        StatusNormalSecondBean secondBean = new StatusNormalSecondBean(
                                                g.getData().get(i).getCarNo(),
                                                g.getData().get(i).getCarId(),
                                                g.getData().get(i).getStatus(),
                                                g.getData().get(i).getIsConsummate(),
                                                g.getData().get(i).getCarDriverId(),
                                                g.getData().get(i).getIsTrailerCarInfo()
                                        );


                                        if (g.getData().get(i).getStatus() == 0) {
                                            StatusTabbeddNormalBean statusNormalBean = new StatusTabbeddNormalBean(g.getData().get(i).getCarInfo(), g.getData().get(i).getStatus(), g.getData().get(i).getIsTrailerCarInfo());
                                            secondBean.addSubItem(statusNormalBean);
                                            list.add(secondBean);

                                        } else {

                                            StatusTabbeddNormalBean statusNormalBean = new StatusTabbeddNormalBean(
                                                    g.getData().get(i).getCarInfo(),
                                                    g.getData().get(i).getCarStatus().getDriverPhoto(),
                                                    g.getData().get(i).getCarStatus().getDriverName(),
                                                    g.getData().get(i).getCarStatus().getOrderCtime(),
                                                    g.getData().get(i).getCarStatus().getDriverMobile(),
                                                    g.getData().get(i).getStatus(),
                                                    g.getData().get(i).getIsConsummate(),
                                                    g.getData().get(i).getCarDriverId(),
                                                    g.getData().get(i).getIsTrailerCarInfo()


                                            );

                                            secondBean.addSubItem(statusNormalBean);
                                            list.add(secondBean);


                                        }

                                    }


                                }

                                carnumberadapter = new SelectCarNumberNewBeanAdapter(list);


                                final GridLayoutManager manager = new GridLayoutManager(context, 1);


                                type.setLayoutManager(manager);
                                type.setAdapter(carnumberadapter);


                                carnumberadapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                                    @Override
                                    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                                        switch (view.getId()) {
                                            case R.id.check_select:
                                                if (selectone == -1) {
                                                    StatusNormalSecondBean multiItemEntity = (StatusNormalSecondBean) carnumberadapter.getData().get(position);
                                                    multiItemEntity.setIsselect(true);
                                                    carnumberadapter.notifyItemChanged(position);
                                                    selectone = position;

                                                } else if (selectone != position) {
                                                    StatusNormalSecondBean multiItemEntity = (StatusNormalSecondBean) carnumberadapter.getData().get(selectone);
                                                    multiItemEntity.setIsselect(false);
                                                    carnumberadapter.notifyItemChanged(selectone);
                                                    StatusNormalSecondBean multiItemEntityposition = (StatusNormalSecondBean) carnumberadapter.getData().get(position);
                                                    multiItemEntityposition.setIsselect(true);
                                                    carnumberadapter.notifyItemChanged(position);
                                                    selectone = position;
                                                }
                                                break;
                                            case R.id.callphone:
                                                StatusTabbeddNormalBean statusTabbeddNormalBean = (StatusTabbeddNormalBean) carnumberadapter.getData().get(position);
                                                if (!statusTabbeddNormalBean.phone.isEmpty()) {
                                                    Utils.callPhone(DriverPublishEmptyActivity.this, statusTabbeddNormalBean.phone);
                                                }
                                                break;

                                        }
                                    }
                                });


//                                carnumberadapter.expandAll();

                                builder.setView(view);
                                alertDialog = builder.show();


                            }
                            else {
                                showToast("请到车辆管理添加车辆,才可以抢单");
                                finish();
                                startActivity(DriverVehicleManageActivity.class);

                            }

                        } else if (g.getCode().equals("-1")){
                            showToast(g.getMsg());
                            finish();
                            startActivity(DriverVehicleManageActivity.class);
                        }else {
                            showToast(g.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDig();
                    }
                });
    }

    private void getpseronal() {

        OkGo.<String>get(Comment_PerSonal_Show)

                .params("id", SPUtils.getAccounId(context))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.code() == 200) {
                            PersonalCommentShowBean personal = GsonUtil.parseJsonWithGson(response.body(), PersonalCommentShowBean.class);
                            if (Integer.valueOf(personal.getCode()) == 0) {

                                carName.setText(personal.getData().getUserName());
                                shipperscore.setText(personal.getData().getScore());
                                jiaoyi.setText(String.valueOf(personal.getData().getTransactionsNum()));
                                pingjia.setText(String.valueOf(personal.getData().getEvaluateCount()));
                                commentscore.setText(personal.getData().getLevel());
                                if (personal.getData().getPhoto() != null) {
                                    if (personal.getData().getPhoto().length() > 0) {
                                        Glide.with(DriverPublishEmptyActivity.this).load(personal.getData().getPhoto()).placeholder(R.mipmap.picture).into(shippername);
                                    }
                                }


                            }

                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast(response.message());
                    }
                });
    }
}


